package pro.cherish.smartfile.config.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.core.Ordered;
import pro.cherish.smartfile.config.AppContext;

/**
 * spring环境变量初始化完成事件监听
 *
 * @Description spring环境变量初始化完成事件监听
 * @ClassName EnvPreparedListener
 * @Author lwh
 * @Date 2020/3/23 17:54
 * @Version 1.0
 */
@Slf4j
public class EnvironmentPreparedListener implements SmartApplicationListener {

	private int order = Ordered.HIGHEST_PRECEDENCE + 10;

	private static Class<?>[] EVENT_TYPES = {ApplicationEnvironmentPreparedEvent.class};

	private static Class<?>[] SOURCE_TYPES = {SpringApplication.class, AppContext.class};

	@Override
	public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
		return isAssignableFrom(eventType, EVENT_TYPES);
	}

	@Override
	public boolean supportsSourceType(Class<?> sourceType) {
		return isAssignableFrom(sourceType, SOURCE_TYPES);
	}

	private boolean isAssignableFrom(Class<?> type, Class<?>... supportedTypes) {
		for (Class<?> supportedType : supportedTypes) {
			if (supportedType.isAssignableFrom(type)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		if (event instanceof ApplicationEnvironmentPreparedEvent) {
			AppContext.setEnvironment(((ApplicationEnvironmentPreparedEvent) event).getEnvironment());
		}
	}

	@Override
	public int getOrder() {
		return order;
	}

}
